<?php
namespace app\admin\logic;

class ArticleSort extends Base
{
    public function jumpCommon()
    {
        $class = new \app\common\logic\ArticleSort();
        return $class;
    }

    public function jumpIndex()
    {
        $class = new \app\index\logic\ArticleSort();
        return $class;
    }

    // 获取分类的等级树
    public function getGradeTree($pm = null)
    {
        // pid,notId,subName
        $pid = isset($pm['pid'])?$pm['pid']:0;
        $notId = isset($pm['notId'])?$pm['notId']:-1;
        $subName = isset($pm['subName'])?$pm['subName']:'children';
        $condition = isset($pm['condition'])?$pm['condition']:'';
        $data = db('article_sort')->where('is_del = 0')->where($condition)->select();
        $rt = tree_grade($data, $pid, $notId, $subName);
        return $rt;
    }

    // 获取分类的平级树
    public function getFlatTree($pm)
    {
        // pid,notId,subName
        $pid = isset($pm['pid'])?$pm['pid']:0;
        $notId = isset($pm['notId'])?$pm['notId']:-1;
        $condition = isset($pm['condition'])?$pm['condition']:'';
        $data = db('article_sort')->where('is_del = 0')->where($condition)->select();
        $rt = flat_tree($data, $pid, $notId);
        return $rt;
    }


    public function add($pm)
    {
        $pm['create_time'] = time();
        $rt = db('article_sort')->add($pm);
        return $rt;
    }

    public function edit($pm)
    {
        $pm['edit_time'] = time();
        $rt = db('article_sort')->where('id', $pm['id'])->update($pm);
        return $rt;
    }

    public function del($pm)
    {
        $list = $this->getFlatTree(['pid'=>$pm['id']]);
        $idArr = array_column($list, 'id');
        $idArr[] = $pm['id'];
        $idStr = implode(',', $idArr);
        $update['edit_time'] = time();
        $update['is_del'] = 1;
        $rt = db('article_sort')->where("id in ({$idStr})")->update($update);
        // 软删除文章
        $this->logic()->article()->del(['condition'=>"sort_id in ({$idStr})"]);
        return $rt;
    }

    public function getNameById($id)
    {
        return db('article_sort')->where('id = '.$id)->value('name');
    }


    public function getTables($pm)
    {
        $condition = isset($pm['condition'])?$pm['condition']:[];
        $where = [];
        if (!empty($pm['name'])) {
            $where[] = "name like '%{$pm['name']}%'";
        }
        $sort = db('article_sort')->where('is_del = 0')->select();
        $list = db('article_sort')->where('is_del = 0')->where($where)->where($condition)->page($pm['page'], $pm['limit'])->select();
        $count = db('article_sort')->where('is_del = 0')->where($where)->where($condition)->select();
        foreach ($list as &$item) {
            $item['crumbs'] = crumbs($sort, $item['pid']);
            $item['create_date'] = admin_date($item['create_time']);
            $item['edit_date'] = admin_date($item['edit_time']);
        }
        return ['data'=>$list, 'count'=>$count];
    }

}